import React, { useState, useEffect } from 'react';
import Footer from '../../components/footer/footer';
import 瑜伽1 from '../../assets/homeimg/瑜伽1.webp';
import 瑜伽2 from '../../assets/homeimg/瑜伽2.webp';
import 瑜伽3 from '../../assets/homeimg/瑜伽3.webp';

const images = [瑜伽1, 瑜伽2, 瑜伽3];

const Carousel = () => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [startX, setStartX] = useState(0);

  // 监听触摸事件，根据滑动距离判断是向左滑还是向右滑
  const handleTouchStart = (event) => {
    setStartX(event.touches[0].clientX);
  };

  const handleTouchEnd = (event) => {
    const endX = event.changedTouches[0].clientX;
    const deltaX = startX - endX;

    if (deltaX > 50) {
      // 向左滑动，切换到下一张图片
      setCurrentIndex((prevIndex) => (prevIndex === images.length - 1 ? 0 : prevIndex + 1));
    } else if (deltaX < -50) {
      // 向右滑动，切换到上一张图片
      setCurrentIndex((prevIndex) => (prevIndex === 0 ? images.length - 1 : prevIndex - 1));
    }

    // 添加滚动动画
    event.target.style.transition = 'transform 0.3s ease-in-out';
    event.target.style.transform = `translateX(-${currentIndex * 100}%)`;

    // 滚动到最后一张图片后，跳到第一张图片
    if (currentIndex === images.length - 1) {
      setTimeout(() => {
        setCurrentIndex(0);
        event.target.style.transition = 'none';
        event.target.style.transform = `translateX(0)`;
      }, 300);
    }
  };

  // 每 3 秒执行一次 setCurrentIndex，更新当前轮播图的索引值
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentIndex((prevIndex) => (prevIndex === images.length - 1 ? 0 : prevIndex + 1));
    }, 3000);
    return () => clearInterval(timer);
  }, [currentIndex]);

  return (
    <>
      <div style={{ height: 'calc(100vh - 60px)', overflowY: 'auto', overflow: 'hidden' }}>
        <div style={{ width: '100%', height: '200px', borderRadius: '20px', border: '1px solid #000' }}></div>
        <div
          style={{
            width: '100%',
            height: '300px',
            overflow: 'hidden',
            position: 'relative',
            borderRadius: '20px',
          }}
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        >
          <div
            style={{
              height: "300px",
              display: 'flex',
              transition: 'transform 0.3s ease-in-out',
              transform: `translateX(-${currentIndex * 100}%)`,
            }}
          >
            {images.map((image, index) => (
              <img
                key={index}
                src={image}
                alt={`Image ${index}`}
                style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '20px' }}
              />
            ))}
          </div>
        </div>
      </div>
      <Footer />
    </>
  );
};

export default Carousel;
